﻿
import java.util.Random;

public class RandomStrategyWithEyes implements Strategy 
{
	private int width;
	private int height;
	public int SelectDirection(Thing map[][], int xMonster, int yMonster, int xPacman, int yPacman)
	{
		width = map.length;
		height = map[0].length;
		int WerePacman = PacmanAndMonster(map, xMonster, yMonster, xPacman, yPacman);
		if (WerePacman == -1)
		{
			int dir = new Random().nextInt(4);
			if ((dir == 0) && ((yMonster == 0) || ((map[xMonster][yMonster-1] != null) && (map[xMonster][yMonster-1].getClass() == Wall.class)))) {
				return SelectDirection(map, xMonster, yMonster, xPacman, yPacman);
			}
			if ((dir == 1) && ((xMonster == width-1) || ((map[xMonster+1][yMonster] != null) && (map[xMonster+1][yMonster].getClass() == Wall.class)))) {
				return SelectDirection(map,  xMonster, yMonster, xPacman, yPacman);
			}
			if ((dir == 2) && ((yMonster == height-1) || ((map[xMonster][yMonster+1] != null) && (map[xMonster][yMonster+1].getClass() == Wall.class)))) {
				return SelectDirection(map,  xMonster, yMonster, xPacman, yPacman);
			}
			if ((dir == 3) && ((xMonster == 0) || ((map[xMonster-1][yMonster] != null) && (map[xMonster-1][yMonster].getClass() == Wall.class)))) {
				return SelectDirection(map, xMonster, yMonster, xPacman, yPacman);	
			}		
			return dir;
		}
		else return WerePacman;
	}
	
	 public int PacmanAndMonster(Thing map[][], int xMonster, int yMonster, int xPacman, int yPacman)
	 {
		 int x = xMonster;
		 int y = yMonster;
		 if(xPacman != xMonster && yPacman != yMonster)
		 {
			 return -1;
		 }
		 while (y > 0 && map[x][y].getClass() != Wall.class)
		 {
			 
			 y--;
			 if  (x == xPacman && y == yPacman)
			 {
				 return 0;
			 }
			 
		 }
		 
		 
		 x = xMonster;
		 y = yMonster;
		 while (x < width-1 && map[x][y].getClass() != Wall.class)
		 {
			 x++;
			 if  (x == xPacman && y == yPacman)
			 {
				 return 1;
			 }
			 
		 }
		 
		 
		 x = xMonster;
		 y = yMonster;
		 while (y < height-1 && map[x][y].getClass() != Wall.class)
		 {
			 y++;
			 if  (x == xPacman && y == yPacman)
			 {
				 return 2;
			 }
			 y++;
		 }
		 
		 
		 x = xMonster;
		 y = yMonster;
		 while (x > 0 && map[x][y].getClass() != Wall.class)
		 {
			 x--;
			 if  (x == xPacman && y == yPacman)
			 {
				 return 3;
			 }
			 x--;
		 }
		 return -1;
	 }
}
